﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace TiebaSignWP7
{
    class WAPSigner
    {
        public WAPSigner(CookieContainer cc, List<string> pls, string ptbs, string pformat)
        {
            this.tcc = cc;
            this.ls = pls;
            this.tbs = ptbs;
            this.format = pformat;
        }

        private CookieContainer tcc = new CookieContainer();
        private List<string> ls = new List<string>();
        private string tbs = "";
        private string format = "";
        private bool isAsyncComplete = false;
        private List<string> updateInfoList = new List<string>();

        public delegate void WAPSignerDelegate(List<string> tls, List<string> updateLs);
        public delegate void WAPSignerSCompleteDelegate(bool isSignComplete);
        public WAPSignerDelegate wsd;
        public WAPSignerSCompleteDelegate wsscd;

        internal void Sign()
        {
            isAsyncComplete = true;
            foreach (string url in ls)
            {
                while (isAsyncComplete == false)
                { }
                try
                {
                    isAsyncComplete = false;
                    GetPage("http://tieba.baidu.com/mo/q---" + format
                                                + "sign?tbs=" + tbs + "&fid=" + url.Split(',')[4]
                                                + "&kw=" + url.Split(',')[5]);
                }
                catch (Exception ex)
                {
                    ex.ToString();
                    updateInfoList.Add("异常");
                    wsd(ls, updateInfoList);
                    isAsyncComplete = true;
                }
            }
            while (isAsyncComplete == false)
            { }
            wsscd(true);
        }

        private void GetPage(string tiebaUrl)
        {
            string url = tiebaUrl;
            //创建WebRequest类
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            if (tcc == null)
                tcc = new CookieContainer();
            request.CookieContainer = tcc;
            request.Method = "GET";
            //返回异步操作的状态
            IAsyncResult result = (IAsyncResult)request.BeginGetResponse(GetPageResponse, request);
        }

        private void GetPageResponse(IAsyncResult result)
        {
            string webPageContentString = "";
            //获取异步操作返回的的信息
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;
            //结束对 Internet 资源的异步请求
            WebResponse response = request.EndGetResponse(result);
            //avoid multi-dispose by try finally segment
            Stream strm = null;
            try
            {
                strm = response.GetResponseStream();
                using (StreamReader sreader = new StreamReader(strm))
                {
                    strm = null;
                    webPageContentString = sreader.ReadToEnd();
                    HandlePageException(webPageContentString);
                }
            }
            finally
            {
                if (strm != null)
                    strm.Dispose();
            }
        }

        private void HandlePageException(string webPageContentString)
        {
            if (webPageContentString.Contains("签到成功"))
            { RegularSignSuccess(webPageContentString); }
            else if (webPageContentString.Contains("已经签过了"))
            { updateInfoList.Add("已经签过了"); }
            else if (webPageContentString.Contains("尚未建立"))
            { updateInfoList.Add("尚未建立"); }
            else if (webPageContentString.Contains("操作未成功"))
            { updateInfoList.Add("操作未成功"); }
            else
            { updateInfoList.Add("不知道什么情况。。。"); }
            wsd(ls, updateInfoList);
            isAsyncComplete = true;
        }

        private void RegularSignSuccess(string webPageContentString)
        {
            string rs = "(签到成功，经验值上升<span class=\"light\">)(.*?)(</span><br/></span><div class=\"bc\">)(.*?)(吧&#160)";
            Regex r = new Regex(rs, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            Match m = r.Match(webPageContentString);
            for (; m.Success; m = m.NextMatch())
            {
                updateInfoList.Add("签到成功,经验值上升" + m.Groups[2].ToString());
            }
        }
    }
}
